const express = require("express");
const qs = require("querystring");
const db = require("../../config/dbserver.js");
const url = require("url");
const router = express.Router();
const axios = require("axios");

router.get("/", async (req, res) => {
  const query = req.query;
  const { callbackurl, imei, oaid } = query;
  console.log("oaid >>>>>>>>>>>>>>>", oaid);

  await db.dbQuery(
    `INSERT INTO track (oaid,callbackurl,baoguang_id,create_time) VALUES (?,?,?,now())`,
    [oaid, decodeURIComponent(callbackurl), "no parse"]
  );
  // 这里去查 log1 表的 oaid 只有存在就回传
  const [log1Data] = await db.dbQuery(`SELECT * FROM log1 WHERE oaid = ? `, [
    oaid
  ]);
  if (log1Data) {
    // 说明用户已经打开了应用

    const eventType = 5;
    let cbl = callbackurl || "";
    cbl = cbl.replace("__PAYMENT_AMOUNT__", 0);

    const sep = callbackurl.includes("?") ? "&" : "?";
    const sendCallbackUrl = `${cbl}${sep}event_type=${eventType}`;
    try {
      const result = await axios.get(sendCallbackUrl);
      console.log(result.data);
      setErrorInfoToLog1(oaid, {
        type: "回传成功 类型:5",
        detail: "爱奇艺请求服务器尝试回传 (type = 5)",
        content: JSON.stringify(result.data),
        oaid,
        callback: sendCallbackUrl
      });
    } catch (error) {
      console.log("回传失败", error.response?.data);
      setErrorInfoToLog1(oaid, {
        type: "回传失败 类型:5",
        detail: "爱奇艺请求服务器尝试回传失败 (type = 5)",
        content: JSON.stringify(error.response?.data || error),
        oaid
      });
    }
  }

  // res.send(query)
  res.status(200).send({
    data: query,
    a: url.parse(callbackurl),
    callbackurl: decodeURIComponent(callbackurl),
    parse: qs.parse(url.parse(callbackurl).query)
  });
});

const simdjson = require("simdjson");
async function setErrorInfoToLog1(oaid, obj = {}) {
  // 先取出 log1 表的 oaid 条
  const [log1Data] = await db.dbQuery(`SELECT * FROM log1 WHERE oaid = ? `, [
    oaid
  ]);
  if (log1Data) {
    let errorInfo;
    if (simdjson.isValid(log1Data.error) && log1Data.error) {
      errorInfo = simdjson.parse(log1Data.error);
    } else {
      errorInfo = {
        info: []
      };
    }
    errorInfo.info.push(obj);
    // 更新sql
    await db.dbQuery("UPDATE log1 SET error = ? WHERE oaid = ?", [
      JSON.stringify(errorInfo),
      oaid
    ]);
  } else {
    console.error("添加回传错误信息失败 这是不正常的 回传信息", oaid);
  }
}

router.get("/hand", async (req, res) => {
  const { oaid, platform } = req.query;

  if (!oaid) {
    return res.status(200).send({
      code: 200,
      data: { callbackurl: "" },
      message: "oaid 不存在"
    });
  }

  try {
    const dbDatas = await db.dbQuery(`SELECT * FROM track WHERE oaid = ? `, [
      oaid
    ]);

    if (!dbDatas.length) {
      await db.dbQuery(
        `INSERT INTO track_log (oaid,vv,create_time) VALUES (?,?,now())`,
        [
          oaid,
          JSON.stringify({
            info: "未查询到指定oaid",
            value: oaid,
            platform
          })
        ]
      );
      console.log("track 追踪回传 未查询到oaid");
      return res.status(200).send({
        code: 0,
        data: { callbackurl: "" },
        message: "未查询到指定oaid"
      });
    }

    console.log("检测地址回传执行 ---------------------");
    console.log(dbDatas.length);
   await Promise.all(
      dbDatas.map(async (dbData) => {
        const eventType = 27;
        let cbl = dbData.callbackurl || "";
        cbl = cbl.replace("__PAYMENT_AMOUNT__", 0);
        const sep = cbl.includes("?") ? "&" : "?";
        const sendCallbackUrl = `${cbl}${sep}event_type=${eventType}`;
        return axios.get(sendCallbackUrl);
      })
    )
      .then(async (resp) => {
        console.log("hand promise all ------------", resp);
        await db.dbQuery(`UPDATE log1 SET track = ? WHERE oaid = ? `, [
          1,
          oaid
        ]);

        return res.status(200).send({
          code: 200,
          data: {
            oaid
            // result: Object.assign({}, result.data)
          },
          message: "回传成功"
        });
      })
      .catch(async (error) => {
        console.log("回传失败------", error.response?.data || error);
        await setErrorInfoToLog1(oaid, {
          type: "回传失败",
          detil: "描述: 此错误信息为请求回传的响应错误结果",
          content: JSON.stringify(error.response?.data ?? error),
          oaid,
          platform
        });
        return res.status(200).send({
          code: 0,
          data: { result: error.response?.data || error },
          message: "回传失败"
        });
      });
  } catch (e) {
    console.error("/hand 路由内部错误:", e);
    return res.status(200).send({
      code: 0,
      data: { callbackurl: "" },
      message: "服务器内部错误"
    });
  }
});

// 查找oaid 是否有监测地址
router.get("/find", async (req, res) => {
  try {
    const { oaid } = req.query;

    if (!oaid) {
      return res.status(400).send({
        code: 400,
        data: {},
        message: "参数 oaid 缺失"
      });
    }

    const [dbData, ...other] = await db.dbQuery(
      `SELECT * FROM track WHERE oaid = ?`,
      [oaid]
    );

    if (dbData) {
      return res.status(200).send({
        code: 200,
        data: dbData,
        other: other.length > 0 ? other : undefined,
        message: "查询成功"
      });
    } else {
      return res.status(200).send({
        code: 0,
        data: {},
        message: "未查询到指定 oaid"
      });
    }
  } catch (error) {
    console.error("查询失败: ", error);
    return res.status(500).send({
      code: 500,
      data: {},
      message: "服务器内部错误"
    });
  }
});

module.exports = router;
